import axios from 'axios'
const cheerio = require('cheerio')
//创建axios实例
const instance = axios.create({
  // baseURL: 'https://www.17k.com/',
})

//响应拦截器
instance.interceptors.response.use(response => {
  return response.data //请求成功提取data数据
}, error => {
  throw error.response.data; //抛出错误data数据
})

export { instance } //导出axios实例
// ***PUBLIC FUNCTION*** //

//获取搜索联想词汇
function getImagineWords(args) {
  //args[1]为搜索内容
  let imagineWords = []//联想词汇数组
  let startms = new Date().getTime() //开始时间戳
  // 第一个笔趣阁
  // let bqg1 = () => instance.get('/bqg1/modules/article/search.php?searchkey=' + args[1])
  let bqg1 = () => instance({
    url: 'http://www.b5200.org/modules/article/search.php?searchkey=' + args[1],
    headers: {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin":"*"
    }
  })
  // 第二个笔趣阁
  let bqg2 = () => instance({
    url: '/bqg2/case.php?m=search',
    method: 'post',
    data: 'key=' + args[1],
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  })
  // 第三个笔趣阁
  let bqg3 = () => instance.get('/bqg3/s.php?ie=gbk&q=' + args[1])
  // 第四个笔趣阁
  let bqg4 = () => instance({
    url: '/bqg4/search/',
    method: 'post',
    data: 'searchkey=' + args[1] + '&Submit=搜索',
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Upgrade-Insecure-Requests": 1
    }
  })
  // 第五个笔趣阁
  let bqg5 = () => instance({
    url: '/bqg5/search.php',
    method: 'post',
    data: 'keyword=' + args[1],
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Upgrade-Insecure-Requests": 1
    }
  })
  // 第六个笔趣阁
  let bqg6 = () => instance({
    url: '/bqg6/search.php?keyword=' + args[1],
    method: 'get',
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Upgrade-Insecure-Requests": 1
    }
  })
  //并发请求
  return axios.all([bqg1(), bqg2(), bqg3(), bqg4(), bqg5(), bqg6()]).then(axios.spread((data1, data2, data3, data4, data5, data6) => {
    console.log(data1)
    console.log(data3)
    let $ = cheerio.load(data1) //加载html
    for (let i = 2; i < $('#hotcontent > table > tbody').children().length + 1; i++) {
      imagineWords.push($('#hotcontent > table > tbody > tr:nth-child(' + i + ') > td:nth-child(1) > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    $ = cheerio.load(data2) //加载html
    for (let i = 1; i < $('#newscontent > div.l > ul').children().length + 1; i++) {
      imagineWords.push($('#newscontent > div.l > ul > li:nth-child(' + i + ') > span.s2 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    $ = cheerio.load(data3) //加载html
    for (let i = 1; i < $('body > div.wrap > div > div').children().length + 1; i++) {
      imagineWords.push($('body > div.wrap > div > div > div:nth-child(' + i + ') > div > div.bookinfo > h4 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    $ = cheerio.load(data4) //加载html
    for (let i = 2; i < $('body > div.container > div > div > ul').children().length + 1; i++) {
      imagineWords.push($('body > div.container > div > div > ul > li:nth-child(' + i + ') > span.s2 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    $ = cheerio.load(data5) //加载html
    for (let i = 2; i < $('#search-main > div.search-list > ul').children().length + 1; i++) {
      imagineWords.push($('#search-main > div.search-list > ul > li:nth-child(' + i + ') > span.s2 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    $ = cheerio.load(data6) //加载html
    for (let i = 1; i < $('#wrapper > div.result-list.gameblock-result-list').children().length + 1; i++) {
      imagineWords.push($('#wrapper > div.result-list.gameblock-result-list > div:nth-child(' + i + ') > div.result-game-item-detail > h3 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    let set = new Set(imagineWords) //数组去重
    imagineWords = [...set].filter(item => item) //去掉数组中空值
    console.log('请求总耗时', new Date().getTime() - startms, 'ms')
    return imagineWords //抛出请求数据
    // console.log(imagineWords)
  }))
}

//获取搜索结果列表信息
function getNovelList(args) {
  //args[1]为搜索内容
  let startms = new Date().getTime() //开始时间戳
  // 第一个笔趣阁
  let bqg1 = () => instance.get('/bqg1/modules/article/search.php?searchkey=' + args[1])
  // 第二个笔趣阁
  let bqg2 = () => instance({
    url: '/bqg2/case.php?m=search',
    method: 'post',
    data: 'key=' + args[1],
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  })
  // 第三个笔趣阁
  let bqg3 = () => instance.get('/bqg3/s.php?ie=gbk&q=' + args[1])
  // 第四个笔趣阁
  let bqg4 = () => instance({
    url: '/bqg4/search/',
    method: 'post',
    data: 'searchkey=' + args[1] + '&Submit=搜索',
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Upgrade-Insecure-Requests": 1
    }
  })
  // 第五个笔趣阁
  let bqg5 = () => instance({
    url: '/bqg5/search.php',
    method: 'post',
    data: 'keyword=' + args[1],
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Upgrade-Insecure-Requests": 1
    }
  })
  // 第六个笔趣阁
  let bqg6 = () => instance({
    url: '/bqg6/search.php?keyword=' + args[1],
    method: 'get',
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Upgrade-Insecure-Requests": 1
    }
  })
  return bqg1().then(data => {
    let $ = cheerio.load(data); //加载html
    //循环获取小说信息
    (async () => {
      for (let i = 2; i < $('#hotcontent > table > tbody').children().length + 1; i++) {
        let url = '/bqg1' + $('#hotcontent > table > tbody > tr:nth-child(' + i + ') > td:nth-child(1) > a')[0].attribs.href.replace('http://www.b5200.org', '')
        await instance.get(url).then(data => {
          const obj = {} //小说大致详情对象
          let $ = cheerio.load(data) //加载html
          obj.name = $('#info > h1').text() //小说名字
          obj.author = $('#info > p:nth-child(2)').text().split('者：')[1] //小说作者
          obj.img = $('#fmimg > img')[0].attribs.src //小说封面
          obj.type = $('#wrapper > div.box_con > div.con_top > a:nth-child(3)').text() //小说类型
          obj.introduce = $('#intro > p').text() //小说简介
          obj.rate = parseFloat((Math.random() * 5 + 5).toFixed(1)) //小说评分
          obj.origin = 'bqg1' //小说来源网站
          obj.url = url //小说首页地址
          args[2](obj)//回调
        }).then(() => {
          //延时等待
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              resolve()
            }, 500);
          })
        })
      }
    })()
  }).then(data => {
    // 第二个笔趣阁
    let promiseArray = []//promise数组
    let startms = new Date().getTime(); //开始时间戳
    bqg2().then(data => {
      let $ = cheerio.load(data) //加载html
      for (let i = 1; i < $('#newscontent > div.l > ul').children().length + 1; i++) {
        // console.log('/bqg2' + $('#newscontent > div.l > ul > li:nth-child(' + i + ') > span.s2 > a')[0].attribs.href)
        let func = (() => {
          return instance.get('/bqg2' + $('#newscontent > div.l > ul > li:nth-child(' + i + ') > span.s2 > a')[0].attribs.href)
        })()
        promiseArray.push(func)
      }
      //并发请求获取小说信息
      return axios.all(promiseArray)
    }).then(axios.spread((...datas) => {
      for (let item of datas) {
        let $ = cheerio.load(item) //加载html
        const obj = {} //小说大致详情对象
        obj.name = $('#info > h1').text() //小说名字
        obj.author = $('#info > p:nth-child(2)').text().split('者：')[1] //小说作者
        obj.img = $('#fmimg > img')[0].attribs.src //小说封面
        obj.type = $('#wrapper > div:nth-child(5) > div.con_top').text() //小说类型
        obj.introduce = $('#intro').text() //小说简介
        obj.rate = parseFloat((Math.random() * 5 + 5).toFixed(1)) //小说评分
        obj.origin = 'bqg2' //小说来源网站
        obj.url = $('head > meta:nth-child(16)') //小说首页地址
        args[2](obj)//回调
      }
      console.log('请求总耗时', new Date().getTime() - startms, 'ms')
    }))

  }).then(data => {
    // 第三个笔趣阁
    let startms = new Date().getTime(); //开始时间戳
    bqg3().then(data => {
      let $ = cheerio.load(data) //加载html
      for (let i = 1; i < $('body > div.wrap > div > div').children().length + 1; i++) {
        const obj = {} //小说大致详情对象
        obj.name = $('body > div.wrap > div > div > div:nth-child(' + i + ') > div > div.bookinfo > h4 > a').text() //小说名字
        obj.author = $('body > div.wrap > div > div > div:nth-child(' + i + ') > div > div.bookinfo > div.author').text().split('作者：')[1] //小说作者
        obj.img = 'http://www.ibiquge.com' + $('body > div.wrap > div > div > div:nth-child(' + i + ') > div > div.bookimg > a > img')[0].attribs.src //小说封面
        obj.type = $('body > div.wrap > div > div > div:nth-child(' + i + ') > div > div.bookinfo > div.cat').text().split('分类：')[1]  //小说类型
        obj.introduce = $('body > div.wrap > div > div > div:nth-child(' + i + ') > div > div.bookinfo > p').text() //小说简介
        obj.rate = parseFloat((Math.random() * 5 + 5).toFixed(1)) //小说评分
        obj.origin = 'bqg3' //小说来源网站
        obj.url = '/bqg3' + $('body > div.wrap > div > div > div:nth-child(' + i + ') > div > div.bookinfo > h4 > a')[0].attribs.href //小说首页地址
        args[2](obj)//回调
      }
      console.log('请求总耗时', new Date().getTime() - startms, 'ms')
    })
  })


  return


  //并发请求
  return axios.all([bqg1(), bqg2(), bqg3(), bqg4(), bqg5(), bqg6()]).then(axios.spread((data1, data2, data3, data4, data5, data6) => {
    let $ = cheerio.load(data1) //加载html
    let promiseArray = []//promise数组
    let startms = new Date().getTime(); //开始时间戳

    // console.log(imagineWords)
    $ = cheerio.load(data2) //加载html
    for (let i = 1; i < $('#newscontent > div.l > ul').children().length + 1; i++) {
      imagineWords.push($('#newscontent > div.l > ul > li:nth-child(' + i + ') > span.s2 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    $ = cheerio.load(data3) //加载html
    for (let i = 1; i < $('body > div.wrap > div > div').children().length + 1; i++) {
      imagineWords.push($('body > div.wrap > div > div > div:nth-child(' + i + ') > div > div.bookinfo > h4 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    $ = cheerio.load(data4) //加载html
    for (let i = 2; i < $('body > div.container > div > div > ul').children().length + 1; i++) {
      imagineWords.push($('body > div.container > div > div > ul > li:nth-child(' + i + ') > span.s2 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    $ = cheerio.load(data5) //加载html
    for (let i = 2; i < $('#search-main > div.search-list > ul').children().length + 1; i++) {
      imagineWords.push($('#search-main > div.search-list > ul > li:nth-child(' + i + ') > span.s2 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    $ = cheerio.load(data6) //加载html
    for (let i = 1; i < $('#wrapper > div.result-list.gameblock-result-list').children().length + 1; i++) {
      imagineWords.push($('#wrapper > div.result-list.gameblock-result-list > div:nth-child(' + i + ') > div.result-game-item-detail > h3 > a').text().replace(/\s|[\r\n]/g, ''))
    }
    // console.log(imagineWords)
    let set = new Set(imagineWords) //数组去重
    imagineWords = [...set].filter(item => item) //去掉数组中空值
    console.log('请求总耗时', new Date().getTime() - startms, 'ms')
    return imagineWords //抛出请求数据
    // console.log(imagineWords)
  }))
}

const obj = {
  getImagineWords,
  getNovelList
}

//入口函数
function spider(...args) {
  //0函数名，1爬虫项目名，后面其他参数
  console.log(args)
  try {
    console.log(args[0] + '(args)')
    return eval(obj[args[0]](args))
    return eval(args[0] + '(args)')
  }
  catch {
    console.log('出错')
    return require('./' + args[1]).default(args)
  }
}

//导出入口函数
export default spider
